package org.vergil.utils.secure;

import javax.crypto.Cipher;
import javax.crypto.NoSuchPaddingException;
import java.security.*;
import java.util.Base64;

/**
 * @author: vergil
 * @Date: 2018/5/20
 * @Description:
 */
public class RSA {

    private static final String ALGORITHM = "RSA";
    private KeyPairGenerator keyPairGenerator;
    private KeyPair keyPair;
    private Cipher cipher;

    RSA() throws NoSuchPaddingException, NoSuchAlgorithmException {
        keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom random = new SecureRandom();
        keyPairGenerator.initialize(1024, random);
        keyPair = keyPairGenerator.generateKeyPair();
        keyPairGenerator.genKeyPair();
        cipher = Cipher.getInstance(ALGORITHM);
    }

    RSA(int keySize) throws NoSuchPaddingException, NoSuchAlgorithmException {
        keyPairGenerator = KeyPairGenerator.getInstance(ALGORITHM);
        SecureRandom random = new SecureRandom();
        keyPairGenerator.initialize(keySize, random);
        keyPair = keyPairGenerator.generateKeyPair();
        keyPairGenerator.genKeyPair();
        cipher = Cipher.getInstance(ALGORITHM);
    }

    /**
     * 获取公钥
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public PublicKey getPublicKey(){
       return keyPair.getPublic();
    }

    /**
     * 获取私钥
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public PrivateKey getPrivateKey(){
        return keyPair.getPrivate();
    }

    /**
     * 公钥加密
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public String encrypt(String content, PublicKey publicKey) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        byte[] encryptBytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encryptBytes);
    }

    /**
     * 私钥解密
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public String decrypt(String content, PrivateKey privateKey) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(decryptBytes);
    }

    /**
     * 公钥加密
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public String encrypt(String content, PrivateKey privateKey) throws Exception {
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        byte[] encryptBytes = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encryptBytes);
    }

    /**
     * 公钥解密
     *
     * @auther: vergil
     * @date: 2018/5/20
     */
    public String decrypt(String content, PublicKey publicKey) throws Exception {
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        byte[] decryptBytes = cipher.doFinal(Base64.getDecoder().decode(content));
        return new String(decryptBytes);
    }
}
